<script setup lang="ts">
import { computed, ref, onMounted } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import AddRecord from './AddRecord.vue'

// 注册必须的组件
use([
  CanvasRenderer,
  LineChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

const props = defineProps<{
  records: Array<{
    id: number
    name: string
    type: string
    date: string
    amount: number
  }>
  showAddForm: { [key: string]: boolean }
}>()

const emit = defineEmits(['toggle-add-form', 'add-success'])

// 按月分组记录
const monthlyRecords = computed(() => {
  const groups: {[key: string]: typeof props.records} = {}
  props.records.forEach(record => {
    const monthKey = record.date.slice(0, 7) // 获取 YYYY-MM 格式
    if (!groups[monthKey]) {
      groups[monthKey] = []
    }
    groups[monthKey].push(record)
  })
  return groups
})

// 计算月统计数据
const getMonthlyStats = (records: typeof props.records) => {
  return {
    income: records.filter(r => r.type === '收入').reduce((sum, r) => sum + r.amount, 0),
    expense: records.filter(r => r.type === '支出').reduce((sum, r) => sum + r.amount, 0)
  }
}

// 图表配置
const chartOption = computed(() => {
  const months = Object.keys(monthlyRecords.value).sort()
  const incomeData = months.map(month => getMonthlyStats(monthlyRecords.value[month]).income)
  const expenseData = months.map(month => getMonthlyStats(monthlyRecords.value[month]).expense)
  const balanceData = months.map((month, index) => incomeData[index] - expenseData[index])

  return {
    title: {
      text: '月度收支趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        let result = `${params[0].axisValue}<br/>`
        params.forEach((param: any) => {
          const value = param.value.toLocaleString('zh-CN', {
            style: 'currency',
            currency: 'CNY'
          })
          result += `${param.seriesName}: ${value}<br/>`
        })
        return result
      }
    },
    legend: {
      data: ['收入', '支出', '结余'],
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '60px',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: months,
      boundaryGap: false
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: (value: number) => {
          return value.toLocaleString('zh-CN', {
            style: 'currency',
            currency: 'CNY',
            minimumFractionDigits: 0,
            maximumFractionDigits: 0
          })
        }
      }
    },
    series: [
      {
        name: '收入',
        type: 'line',
        data: incomeData,
        itemStyle: {
          color: '#52c41a'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0,
              color: 'rgba(82, 196, 26, 0.2)'
            }, {
              offset: 1,
              color: 'rgba(82, 196, 26, 0)'
            }]
          }
        },
        smooth: true
      },
      {
        name: '支出',
        type: 'line',
        data: expenseData,
        itemStyle: {
          color: '#f5222d'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0,
              color: 'rgba(245, 34, 45, 0.2)'
            }, {
              offset: 1,
              color: 'rgba(245, 34, 45, 0)'
            }]
          }
        },
        smooth: true
      },
      {
        name: '结余',
        type: 'line',
        data: balanceData,
        itemStyle: {
          color: '#1890ff'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0,
              color: 'rgba(24, 144, 255, 0.2)'
            }, {
              offset: 1,
              color: 'rgba(24, 144, 255, 0)'
            }]
          }
        },
        smooth: true
      }
    ]
  }
})
</script>

<template>
  <div class="month-view">
    <!-- 图表区域 -->
    <div class="chart-container">
      <v-chart class="chart" :option="chartOption" autoresize />
    </div>

    <!-- 月度明细 -->
    <div v-for="(monthRecords, monthKey) in monthlyRecords" :key="monthKey" class="month-group">
      <!-- 原有的月度内容 -->
      <div class="month-header">
        <h2>{{ monthKey }}</h2>
        <div class="monthly-summary">
          <span class="income-text">月收入: ¥{{ getMonthlyStats(monthRecords).income }}</span>
          <span class="expense-text">月支出: ¥{{ getMonthlyStats(monthRecords).expense }}</span>
          <span class="balance-text">
            结余: ¥{{ getMonthlyStats(monthRecords).income - getMonthlyStats(monthRecords).expense }}
          </span>
        </div>
      </div>

      <div class="records">
        <!-- 原有的记录内容 -->
        <div class="record-header">
          <span class="col name">名称</span>
          <span class="col type">类型</span>
          <span class="col category">种类</span>
          <span class="col remark">备注</span>
          <span class="col spacer">日期</span>
          <span class="col amount">金额</span>
        </div>
        <div v-for="record in monthRecords" :key="record.id" class="record-item">
          <span class="col name">{{ record.name }}</span>
          <span class="col type">
            <span class="type-tag" :class="record.type === '收入' ? 'income' : 'expense'">
              <i :class="record.type === '收入' ? 'fa fa-plus-circle' : 'fa fa-minus-circle'"></i>
              <span class="type-text">{{ record.type }}</span>
            </span>
          </span>
          <span class="col category">
            <span class="category-tag">{{ record.category }}</span>
          </span>
          <span class="col remark" :title="record.remark">{{ record.remark || '-' }}</span>
          <span class="col spacer">{{ record.date }}</span>
          <span class="col amount" :class="record.type === '收入' ? 'income' : 'expense'">
            {{ record.type === '收入' ? '+' : '-' }}¥{{ record.amount }}
          </span>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.month-view {
  width: 100%;
}

.month-group {
  margin-bottom: 48px;
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.month-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 12px;
  border-bottom: 2px solid #e8e8e8;
}

.month-header h2 {
  margin: 0;
  color: #1890ff;
  font-size: 20px;
}

.monthly-summary {
  display: flex;
  gap: 24px;
  font-size: 16px;
  font-weight: 500;
}

.balance-text {
  color: #1890ff;
  font-weight: bold;
}

.records {
  margin-top: 16px;
}

.record-header {
  display: flex;
  padding: 8px 16px;
  background: #fafafa;
  border-radius: 4px;
  margin-bottom: 8px;
  font-weight: 500;
  color: #666;
}

.record-item {
  display: flex;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
}

.record-item:last-child {
  border-bottom: none;
}

.col {
  display: flex;
  align-items: center;
}

.col.name {
  flex: 1.5;
  padding-right: 16px;
}

.col.type {
  flex: 0.6;
  justify-content: center;
}

.col.category {
  flex: 0.8;
  justify-content: center;
}

.col.remark {
  flex: 1.5;
  color: #666;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.col.spacer {
  width: 150px;
}

.col.amount {
  flex: 0.8;
  justify-content: flex-end;
  font-weight: 500;
}

.type-tag {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.type-text {
  margin-left: 2px;
  color: #333;
}

.type-tag.income {
  background: rgba(82, 196, 26, 0.1);
  border: 1px solid #52c41a;
}

.type-tag.expense {
  background: rgba(245, 34, 45, 0.1);
  border: 1px solid #f5222d;
}

.income-text {
  color: #52c41a;
}

.expense-text {
  color: #f5222d;
}

.income {
  color: #52c41a;
}

.expense {
  color: #f5222d;
}

/* 添加图表相关样式 */
.chart-container {
  background: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.chart {
  height: 400px;
  width: 100%;
}

.category-tag {
  padding: 2px 8px;
  background: #f0f0f0;
  border-radius: 4px;
  font-size: 12px;
  color: #666;
}
</style> 